package com.gy.paidao;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTabHost;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TextView;

import com.gy.paidao.create.CreateBabbleActivity;
import com.gy.paidao.main.MainListFragment;
import com.gy.paidao.main.MainMapFragment;
import com.gy.paidao.main.MainNotificationFragment;
import com.gy.paidao.main.MapGoogleFragment;
import com.gy.paidao.person.LoginActivity;
import com.gy.paidao.setting.SettingMainActivity;
import com.gy.paidao.util.AnimUtil;
import com.gy.paidao.util.HeaderChangeManager;
import com.gy.paidao.util.KeyBoard;
import com.gy.paidao.util.LogUtil;
import com.gy.paidao.util.MainTabEnum;
import com.gy.paidao.util.SPHelper;
import com.jky.struct2.bitmap.FinalBitmap;
import com.jky.struct2.bitmap.FinalBitmapManager;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.ArrayList;

public class MainActivity extends BaseActivity implements View.OnLayoutChangeListener {

    private LinearLayout llMain;
    private ImageView imgLeft, imgRight, imgCenter, imgDelete;
    private View viewEmpty, viewHome;
    private LinearLayout llSearch;
    private EditText etSearch;
    private TextView tvTitle;
    private ImageView imgHead;//头像
    private TextView tvName, tvHome, tvNotifications, tvSet, tvHelp, tvLogout;
    private RelativeLayout main_top;
    private FrameLayout frameLayout;
    private MainListFragment listFragment;
    private MainNotificationFragment notificationFragment;
    private MainMapFragment mapFragment;
    private FragmentManager fragmentManager;
    private MapGoogleFragment googleFragment;
    private Fragment showFragment;
    private MainTabEnum[] mainTabArray = {MainTabEnum.NOTIFICATION, MainTabEnum.HOME, MainTabEnum.MAP};
    //定义FragmentTabHost对象
    private FragmentTabHost mTabHost;
    private LayoutInflater layoutInflater;
    public String mTab;
    private PopupWindow popupWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setViews();
        setData();
    }

    @Override
    protected void initVariable() {
        fragmentManager = getSupportFragmentManager();
        layoutInflater = LayoutInflater.from(this);
        HeaderChangeManager.getInstance().addListener(new HeaderChangeManager.HeaderChangeListener() {
            @Override
            public void headHasChanger() {
                handler.sendEmptyMessage(0);
            }
        });
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(MyApplication.loginBean != null &&
                    !TextUtils.isEmpty(MyApplication.loginBean.headPortrait)){
                FinalBitmap finalBitmap = FinalBitmapManager.getFinalBitmapManager(MainActivity.this).getFinalBitmap(FinalBitmapManager.IMG_SMALL);
                finalBitmap.display(imgHead,MyApplication.loginBean.headPortrait);
            }
        }
    };

    @Override
    protected void setTitleViews() {

    }

    @Override
    protected void setViews() {
        llMain = (LinearLayout) findViewById(R.id.main_ll);
        viewHome = View.inflate(this, R.layout.fg_home_layout, null);
        imgHead = (ImageView) viewHome.findViewById(R.id.fg_home_img_head);
        tvName = (TextView) viewHome.findViewById(R.id.fg_home_tv_name);
        tvHome = (TextView) viewHome.findViewById(R.id.fg_home_tv_home);
        tvNotifications = (TextView) viewHome.findViewById(R.id.fg_home_tv_notification);
        tvSet = (TextView) viewHome.findViewById(R.id.fg_home_tv_setting);
        tvHelp = (TextView) viewHome.findViewById(R.id.fg_home_tv_help);
        tvLogout = (TextView) viewHome.findViewById(R.id.fg_home_tv_logout);

        main_top = (RelativeLayout) findViewById(R.id.main_top);
        imgLeft = (ImageView) findViewById(R.id.main_top_left);
        imgRight = (ImageView) findViewById(R.id.main_top_right);
        imgCenter = (ImageView) findViewById(R.id.main_top_center);
        imgDelete = (ImageView) findViewById(R.id.main_img_delete);
        llSearch = (LinearLayout) findViewById(R.id.main_ll_search);
        etSearch = (EditText) findViewById(R.id.main_et_search);
        viewEmpty = findViewById(R.id.main_view_search_empty);
        tvTitle = (TextView) findViewById(R.id.main_top_title);
        frameLayout = (FrameLayout) findViewById(R.id.realtabcontent);

        //实例化TabHost对象，得到TabHost
        mTabHost = (FragmentTabHost) findViewById(R.id.main_tabhost);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);

        imgLeft.setOnClickListener(this);
        imgRight.setOnClickListener(this);
        imgCenter.setOnClickListener(this);
        imgDelete.setOnClickListener(this);
        viewEmpty.setOnClickListener(this);

        tvHome.setOnClickListener(this);
        tvNotifications.setOnClickListener(this);
        tvSet.setOnClickListener(this);
        tvHelp.setOnClickListener(this);
        tvLogout.setOnClickListener(this);

        initPop();

        llMain.addOnLayoutChangeListener(this);
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    String search = etSearch.getText().toString().trim();
                    if(TextUtils.isEmpty(search)){
                        llSearch.setVisibility(View.GONE);
                    } else {
                        KeyBoard.demissKeyBoard(MainActivity.this,etSearch);
                        viewEmpty.setVisibility(View.GONE);
                        intent = new Intent("search_activity");
                        intent.putExtra("search", search);
                        MainActivity.this.sendBroadcast(intent);
                    }
                    return true;
                }
                return false;
            }
        });

        etSearch.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus){
                    viewEmpty.setVisibility(View.VISIBLE);
                }
            }
        });

        if(MyApplication.loginBean != null &&
                !TextUtils.isEmpty(MyApplication.loginBean.headPortrait)){
            ImageLoader.getInstance().displayImage(MyApplication.loginBean.headPortrait,imgHead);
        }

        if(MyApplication.loginBean != null &&
                !TextUtils.isEmpty(MyApplication.loginBean.nickname)){
            tvName.setText(MyApplication.loginBean.nickname);
        }

    }

    private void setData() {
        int count = mainTabArray.length;

        for (int i = 0; i < count; i++) {
            //为每一个Tab按钮设置图标、文字和内容
            TabHost.TabSpec tabSpec = mTabHost.newTabSpec(getResources().getString(mainTabArray[i].name)).setIndicator(getTabItemView(i));
            //将Tab按钮添加进Tab选项卡中
            mTabHost.addTab(tabSpec, mainTabArray[i].mClass, null);
            //设置Tab按钮的背景
            mTabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.WHITE);
        }
        mTabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
            @Override
            public void onTabChanged(String tabId) {
                mTab = tabId;
                String notify = getResources().getString(R.string.tab_notification);
                String home = getResources().getString(R.string.tab_home);
                String map = getResources().getString(R.string.tab_map);

                if (notify.equals(mTab)) {
                    imgLeft.setVisibility(View.INVISIBLE);
                } else if (home.equals(mTab)) {
                    imgLeft.setVisibility(View.VISIBLE);
                } else if (map.equals(mTab)) {
                    imgLeft.setVisibility(View.INVISIBLE);
                }

            }
        });
        setmCurFragmentetTab(1);
    }

    @Override
    protected void doClickAction(int viewId) {
        super.doClickAction(viewId);
        switch (viewId) {
            case R.id.main_top_left:
                if(llSearch.getVisibility() == View.VISIBLE){
                    llSearch.setVisibility(View.GONE);
                    KeyBoard.demissKeyBoard(this,etSearch);
                } else {
                    llSearch.setVisibility(View.VISIBLE);

                    etSearch.setFocusable(true);
                    etSearch.setFocusableInTouchMode(true);
                    etSearch.requestFocus();
                    KeyBoard.showKeyBoard(this, etSearch);
                    InputMethodManager inputManager = (InputMethodManager) etSearch
                            .getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputManager.showSoftInput(etSearch, 0);
                }

                break;
            case R.id.main_top_right:
                intent = new Intent(this, CreateBabbleActivity.class);
                startActivity(intent);
                break;
            case R.id.main_top_center:
                popupWindow.showAsDropDown(main_top);
                break;
            case R.id.main_img_delete:
                intent = new Intent("search_activity");
                intent.putExtra("search", "");
                MainActivity.this.sendBroadcast(intent);
                etSearch.setText("");
                llSearch.setVisibility(View.GONE);
                KeyBoard.demissKeyBoard(this, etSearch);
                break;
            case R.id.main_view_search_empty:
                llSearch.setVisibility(View.GONE);
                KeyBoard.demissKeyBoard(this, etSearch);
                break;
            case R.id.fg_home_tv_home:
                popupWindow.dismiss();
                break;
            case R.id.fg_home_tv_notification:

                break;
            case R.id.fg_home_tv_setting:
                intent = new Intent(this, SettingMainActivity.class);
                startActivity(intent);
                AnimUtil.pushLeftInAndOut(this);
                break;
            case R.id.fg_home_tv_help:

                break;
            case R.id.fg_home_tv_logout:
                intent = new Intent(this, LoginActivity.class);
                startActivity(intent);
                AnimUtil.pushLeftInAndOut(this);
                SPHelper.getInstance(MainActivity.this).setStringData("userLoginID", "");
                this.finish();
                break;

        }
    }

    private void initPop() {
        popupWindow = new PopupWindow(this);
        popupWindow.setContentView(viewHome);
        popupWindow.setWidth(ViewGroup.LayoutParams.FILL_PARENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.FILL_PARENT);
        popupWindow.setFocusable(true);
        // 实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0x90000000);
        popupWindow.setBackgroundDrawable(dw);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
    }

    /**
     * 给Tab按钮设置图标和文字
     */
    private View getTabItemView(int index) {
        View view = layoutInflater.inflate(R.layout.tab_item_view, null);
        ImageView imageView = (ImageView) view.findViewById(R.id.imageview);
        imageView.setImageResource(mainTabArray[index].imgId);
        TextView textView = (TextView) view.findViewById(R.id.textview);
        textView.setText(mainTabArray[index].name);
        return view;
    }

    public void setmCurFragmentetTab(int index) {
        if (index < mainTabArray.length) {
            mTabHost.setCurrentTab(index);
            Animation animation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.push_left_in);
            animation.setDuration(1000);
            //frameLayout.startAnimation(animation);
        }
    }

    /**
     * 首页根据手势切换view
     *
     * @param flag 左右
     * @param anim 动画
     */
    public void changeByMainList(int flag, int anim) {
        if (flag == 0) {
            setmCurFragmentetTab(0);
        } else if (flag == 2) {
            setmCurFragmentetTab(2);
        }
        Animation in = null, out = null;
        if (anim == 0) {
            in = AnimationUtils.loadAnimation(MainActivity.this, R.anim.push_right_in);
            in.setDuration(1000);
        } else if (anim == 2) {
            in = AnimationUtils.loadAnimation(MainActivity.this, R.anim.push_left_in);
            in.setDuration(1000);
        }
        frameLayout.startAnimation(in);
    }

    @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
        int keyHeight = height / 3;
        //现在认为只要控件将Activity向上推的高度超过了1/3屏幕高，就认为软键盘弹起
        if (oldBottom != 0 && bottom != 0 && (oldBottom - bottom > keyHeight)) {
            mTabHost.setVisibility(View.GONE);
        } else if (oldBottom != 0 && bottom != 0 && (bottom - oldBottom > keyHeight)) {
            mTabHost.setVisibility(View.VISIBLE);
        }
    }


    /**
     * 回调接口
     *
     * @author
     */
    public interface MyTouchListener {
        public void onTouchEvent(MotionEvent event);
    }

    /*
    * 保存MyTouchListener接口的列表
    */
    private ArrayList<MyTouchListener> myTouchListeners = new ArrayList<MyTouchListener>();

    /**
     * 提供给Fragment通过getActivity()方法来注册自己的触摸事件的方法
     *
     * @param listener
     */
    public void registerMyTouchListener(MyTouchListener listener) {
        myTouchListeners.add(listener);
    }

    /**
     * 提供给Fragment通过getActivity()方法来取消注册自己的触摸事件的方法
     *
     * @param listener
     */
    public void unRegisterMyTouchListener(MyTouchListener listener) {
        myTouchListeners.remove(listener);
    }

    /**
     * 分发触摸事件给所有注册了MyTouchListener的接口
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        // TODO Auto-generated method stub
        for (MyTouchListener listener : myTouchListeners) {
            listener.onTouchEvent(ev);
        }
        return super.dispatchTouchEvent(ev);
    }

}
